package com.zj.roseojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.zj.roseojcodesandbox.model.ExecuteCodeRequest;
import com.zj.roseojcodesandbox.model.ExecuteCodeResponse;
import com.zj.roseojcodesandbox.model.ExecuteMessage;
import com.zj.roseojcodesandbox.model.JudgeInfo;
import com.zj.roseojcodesandbox.model.enums.ResponseStatusEnum;
import com.zj.roseojcodesandbox.utils.ProcessUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * JAVA原生实现代码沙箱
 */
@Component
public class JavaNativeCodeSandbox implements CodeSandbox {

    /**
     * 存储用户临时代码文件的目录
     */
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    /**
     * 用户的临时代码的主函数名称
     */
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    /**
     * 时间限制，做超时控制
     */
    private static final long TIME_OUT = 50000L;

    /**
     * 黑名单，用户输入的代码不能包含这些
     */
    private static final List<String> blackList = Arrays.asList("Files","exec");

    /**
     * 字典树
     */
    private static final WordTree WORD_TREE;

    /**
     * 公共安全管理器路径
     */
    private static final String SECURITY_MANAGER_PATH = "D:\\ALLData\\roseoj-code-sandbox\\src\\main\\resources\\security";

    /**
     * 安全管理器类名
     */
    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";

    static { //初始化字典树
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(blackList);
    }


    /**
     * 执行代码，判题
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String language = executeCodeRequest.getLanguage();
        String code = executeCodeRequest.getCode();
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        //校验代码是否包含黑名单中的命令
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if (foundWord != null){
            executeCodeResponse.setMessage("包含敏感词：" + foundWord.getFoundWord());
            executeCodeResponse.setStatus(ResponseStatusEnum.USER_CODE_ERROR.getValue());//用户代码程序错误
            return executeCodeResponse;
        }

        //1.把用户代码保存为临时文件
        //获取到临时代码文件存储目录
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        //把用户的代码隔离存放,根据UUID作为文件名
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2.编译代码，得到.class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            //等待程序执行，获取错误码
            ExecuteMessage compileProcessMessage = ProcessUtils.getProcessMessage(compileProcess, "编译");
            System.out.println(compileProcessMessage);
        } catch (Exception e) {
            return getErrorResponse(e);
        }

        //3.执行编译后的代码
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            //-Xmx256m指令指定最大堆空间大小为256MB
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodePath,SECURITY_MANAGER_PATH,SECURITY_MANAGER_CLASS_NAME,inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                //新开一个线程监听，如果执行超时则中断运行进程
                new Thread(()->{
                    try {
                        Thread.sleep(TIME_OUT);
                        runProcess.destroy();
                        System.out.println("超时中断");
                    } catch (InterruptedException e) {
                        throw new RuntimeException();
                    }
                }).start();
                ExecuteMessage runProcessMessage = ProcessUtils.getProcessMessage(runProcess, "运行");
                System.out.println(runProcessMessage);
                executeMessageList.add(runProcessMessage);
            } catch (IOException e) {
                return getErrorResponse(e);
            }
        }

        //4.收集整理输出结果
        List<String> outputList = new ArrayList<>();
        long maxTime = 0;//取执行程序用时最大值
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) { //返回错误信息相当于用户编写的程序错误
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(ResponseStatusEnum.USER_CODE_ERROR.getValue());//用户代码程序错误
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        //正常运行
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(ResponseStatusEnum.SUCCEED.getValue());
        }
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);//原生JAVA暂不获取内存，太麻烦
        executeCodeResponse.setOutputList(outputList);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        //5.文件清理
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }
        return executeCodeResponse;
    }

    /**
     * 6.错误处理，提升程序健壮性
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        executeCodeResponse.setStatus(ResponseStatusEnum.SANDBOX_ERROR.getValue());//代码沙箱的程序错误
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setOutputList(new ArrayList<>());
        return executeCodeResponse;
    }
}
